package consul

import (
	"fmt"

	"github.com/hashicorp/consul/api"
)

// Consul defines a consul client.
type Consul struct {
	cli *api.Client
}

// NewConsul creates a consul client.
func NewConsul(host string, port int) (*Consul, error) {
	// 连接consul
	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d", host, port)
	cc, err := api.NewClient(cfg)
	if err != nil {
		return nil, err
	}
	return &Consul{cli: cc}, nil
}

func (c *Consul) GetAddr(name string) (string, error) {
	// 返回的是一个 map[string]*api.AgentService
	// 其中key是服务ID，值是注册的服务信息
	serviceMap, err := c.cli.Agent().ServicesWithFilter(fmt.Sprintf(`Service=="%s"`, name))
	if err != nil {
		return "", fmt.Errorf("query service from consul failed, err: %v", err)
	}
	// 选一个服务机（这里选最后一个）
	var addr string
	for _, v := range serviceMap {
		addr = fmt.Sprintf("%s:%d", v.Address, v.Port)
		break
	}
	return addr, nil
}
